import React, { useEffect, useState } from 'react'
import styles from './index.module.less'
import { Button, Checkbox, Space, Toast, Modal } from 'antd-mobile'
import { LeftOutline, } from 'antd-mobile-icons'
import { getCarData, delCarItem, preOrder } from '../../../utils/my/car'
import { useNavigate } from 'react-router-dom'
//接口
interface carType {
    productName: string
    productPic: string
    productSkuId: string
    price: number
    quantity: number
    isChecked: boolean
}
export default function Car() {
    const navigate = useNavigate()
    //购物车数据
    const [carData, setCarData] = useState([])
    //总价格
    const [totalPrice, setTotalPrice] = useState(0)
    //全选按钮
    const [allChecked, setAllChecked] = useState(false)
    //获取购物车列表数据
    const getCarList = async () => {
        let res: resType = await getCarData()
        // console.log(res);
        if (res.code === 20000) {
            let newArr: any = []
            res.data.items.map((item: carType) => {
                newArr.push(Object.assign(item, { isChecked: false }))
            })
            console.log(newArr);
            setCarData(newArr)
        }
    }
    //数量加一
    const addNum = (index: any) => {
        const newList: any = [...carData]
        newList[index].quantity += 1
        setCarData(newList)
    }
    //数量减一 当数量小于1时提示是否删除该商品
    const subNum = (index: any, item: carType) => {
        let arr: any = []
        arr.push(item.productSkuId);
        const subList: any = [...carData]
        subList[index].quantity -= 1
        if (subList[index].quantity < 1) {
            subList[index].quantity = 1
            Modal.confirm({
                content: '是否删除该商品',
                onConfirm: async () => {
                    let res: resType = await delCarItem(arr)
                    // console.log(res);
                    //刷新数据列表
                    if (res.code === 20000) {
                        getCarList()
                        Toast.show({
                            icon: 'sucess',
                            content: "删除成功"
                        })
                    }
                },
                onCancel: () => {
                    Toast.show({
                        icon: 'success',
                        content: '您取消了删除',
                    })
                }
            })
        }
        setCarData(subList)
    }
    //单选按钮
    const itemSelect = (value: boolean, index: any) => {
        const aa: any = [...carData]
        aa[index].isChecked = value
        setCarData(aa)
        sumPrice()
    }
    //全选按钮
    const allSelect = (checked: boolean) => {
        setAllChecked(checked)
        carData.map((item: any) => item.isChecked = checked)
        sumPrice()
    }

    //总计价格
    const sumPrice = () => {
        if (carData.every((item: any) => item.isChecked === true)) {
            setAllChecked(true)
        } else {
            setAllChecked(false)
        }
        let total = 0
        let kun = carData.filter((item: carType) => item.isChecked === true)
        if (kun.length === 0) {
            setTotalPrice(0)
            setAllChecked(false)
        } else {
            kun.map((item: carType) => {
                total += item.price * item.quantity
                setTotalPrice(total)
            })
        }
    }
    //结算价格
    const priceSubmit =async () => {
        const orderInfo={
            orderItemList:[{}]
        } 
      let selArr=carData.filter((item: any) => item.isChecked === true);
    if(selArr){
        //生成负载信息
        selArr.map((item:any,index)=>{
        const orderList={} as any
        orderList['cartId']=item.id
        orderList['productId']=item.productId
        orderList['productQuantity']=item.quantity
        orderList['productSkuId']=item.productSkuId
        orderInfo.orderItemList[index]=orderList
      })   
      //打印最终的载荷信息
    //   console.log(orderInfo);
      let res:resType=await preOrder(orderInfo)
    //   console.log(res);
    if(res.code===20000){
        console.log(res.data.orderId);
        navigate(`/my/order/confirmorder?id=${res.data.orderId}`)
    }
    }
    }
    useEffect(() => {
        getCarList()
        sumPrice()
    }, [])
    //返回上一页
    const backBtn = () => {
        window.history.back()
    }
    return (
        <div>
            <div className={styles.detail_title}>
                <LeftOutline color='#ffffff' fontSize={20} onClick={backBtn} />
                <span>乐居</span>
            </div>
            <div className={styles.car_content}>
                {carData && carData.map((item: carType, index) => (
                    <div className={styles.car_item} key={index}>
                        <div className={styles.car_top}>
                            <Checkbox checked={item.isChecked} onChange={(checked) => itemSelect(checked, index)} />
                            <img src={item.productPic} alt="" />
                            <div className={styles.item_right}>
                                <p style={{ color: 'black', fontSize: '14px' }}>{item.productName}</p>
                                <p><span>编号:{item.productSkuId}</span> <span>价格:￥{item.price}</span> </p>
                                <p>数量:{item.quantity}</p>
                            </div>
                        </div>
                        <div className={styles.car_bottom}>
                            <Space>
                                <Button onClick={() => subNum(index, item)}>-</Button>
                                <span className={styles.num}>{item.quantity}</span>
                                <Button onClick={() => addNum(index)}>+</Button>
                            </Space>
                        </div>
                    </div>
                ))
                }

            </div>
            <div className={styles.footer}>
                <Checkbox checked={allChecked} onChange={(checked) => allSelect(checked)}>全选</Checkbox>
                <div>
                    <span>合计:￥<span style={{ color: 'red' }}>{totalPrice}</span> </span>
                    <Button className={styles.sub_btn} onClick={priceSubmit}>结算</Button>
                </div>

            </div>
        </div>
    )
}
